package org.farm2.main.cecurity.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.farm2.auth.dto.MenusDto;
import org.farm2.auth.service.ActionsServiceInter;
import org.farm2.auth.service.EventLogServiceInter;
import org.farm2.base.db.resource.Farm2SystemResource;
import org.farm2.base.domain.FarmUserContext;
import org.farm2.base.domain.FarmUserContextLoader;
import org.farm2.base.parameter.FarmParameterInter;
import org.farm2.base.password.FarmPasswordEncoder;
import org.farm2.base.web.Farm2WebVisitListenner;
import org.farm2.files.domain.ex.FarmFilePath;
import org.farm2.files.service.ResourceFileServiceInter;
import org.farm2.luser.dto.ResetPasswordDto;
import org.farm2.luser.service.LocalUserServiceInter;
import org.farm2.main.cecurity.dto.KeyDto;
import org.farm2.main.cecurity.service.FarmUserOnlines;
import org.farm2.service.inter.FarmUserServiceInter;
import org.farm2.tools.bean.FarmBeanUtils;
import org.farm2.tools.caches.FarmCaches;
import org.farm2.tools.config.Farm2ConfigEnum;
import org.farm2.tools.config.Farm2ConfigUtils;
import org.farm2.tools.i18n.I18n;
import org.farm2.tools.structure.ResourceInfo;
import org.farm2.tools.web.FarmResponseCode;
import org.farm2.tools.web.FarmResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 当前用户状态
 */
@RestController
@Tag(name = "当前用户相关", description = "登录相关操作的API")
@RequestMapping("/api/current")
public class CurrentController {
    @Autowired
    private FarmParameterInter farmParameter;
    @Autowired
    private FarmUserServiceInter farmUserService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private ActionsServiceInter actionsServiceImpl;
    @Autowired
    private LocalUserServiceInter localUserServiceImpl;
    @Autowired
    private ResourceFileServiceInter resourceFileServiceImpl;
    @Autowired
    private EventLogServiceInter eventLogServiceImpl;


    @Operation(summary = "当前用戶信息(用户和菜单)获取", description = "")
    @PostMapping(value = "/user")
    @ResponseBody
    public FarmResponseResult user(HttpServletRequest request) {
        FarmUserContext user = new FarmUserContext();
        FarmBeanUtils.copyProperties(FarmUserContextLoader.getCurrentUser(), user);
        user.setPassword("");
        List<MenusDto> menus = farmUserService.getUserMenus(user,"FRAME");
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("menus", menus);
        user.setFrameMenuNum(menus.size());
        return new FarmResponseResult<Map>(FarmResponseCode.SUCESS, map);
    }


    @Operation(summary = "当前系统资源信息", description = "")
    @PostMapping(value = "/resource")
    @ResponseBody
    public FarmResponseResult resource(HttpServletRequest request) {
        FarmFilePath filePath = resourceFileServiceImpl.getBasePath(null);
        Map<String, Object> map = new HashMap<>();
        //磁盘百分比
        {
            ResourceInfo info = Farm2SystemResource.getDiskPercentage(filePath.getBasepath());
            map.put("disk", info);
        }
        {
            //附件数量
            int allnum = resourceFileServiceImpl.getAllNum();
            //临时附件数量
            int freenum = resourceFileServiceImpl.getFreeNum();
            ResourceInfo info = new ResourceInfo("附件量", allnum, freenum);
            map.put("files", info);
        }
        //内存百分比
        {
            ResourceInfo info = Farm2SystemResource.getRamPercentage();
            map.put("ram", info);
        }
        //缓存数量
        {
            ResourceInfo info = FarmCaches.getInstance().getAllSize();
            map.put("cache", info);
        }
        //在线用户
        {
            ResourceInfo info = FarmUserOnlines.getOnlineNum();
            map.put("online", info);
        }
        //事件日志
        {
            ResourceInfo info = eventLogServiceImpl.getAllNum();
            map.put("elog", info);
        }
        //处理器百分比
        {
            ResourceInfo info = Farm2SystemResource.getCpuPercentage();
            map.put("cpu", info);
        }
        //事件流量
        {
            ResourceInfo info = Farm2WebVisitListenner.getCurentNum();
            map.put("visit", info);
        }
        return new FarmResponseResult<Map>(FarmResponseCode.SUCESS, map);
    }





    /**
     * 重置当前用户密码（指定密码）
     *
     * @param data
     * @return
     */
    @Operation(summary = "当前用戶密码修改", description = "")
    @PostMapping("/reset.password")
    public FarmResponseResult resetPassword(@RequestBody ResetPasswordDto data) {
        FarmPasswordEncoder passwordEncoder = new FarmPasswordEncoder();
        FarmUserContext currentUser = farmUserService.getUserByLoginName(FarmUserContextLoader.getCurrentUser().getLoginname());
        if (passwordEncoder.matches(data.getWebPassword(), passwordEncoder.getSaltByCode(data.getCode()), currentUser.getPassword())) {
            for (String loginname : data.getUserkeys()) {
                if (loginname.equals(currentUser.getLoginname())) {
                    localUserServiceImpl.resetPasswordByDbPassword(loginname, data.getNewSysPassword());
                } else {
                    throw new RuntimeException(I18n.msg("仅可修改当前用户"));
                }
            }
            return FarmResponseResult.getInstance(FarmResponseCode.SUCESS);
        } else {
            return FarmResponseResult.getInstance(FarmResponseCode.ERROR, FarmPasswordEncoder.MATCHES_FALSEMSG, null);
        }
    }


    @Operation(summary = "读取当前用户配置参数", description = "")
    @PostMapping("/config")
    public FarmResponseResult readConfig(@RequestBody KeyDto key) {
        Set<String> ableKeys = new HashSet<>();
        ableKeys.add("farm2.config.file.length.max");
        ableKeys.add("farm2.config.file.exnames");
        ableKeys.add("farm2.config.sys.title.head");
        ableKeys.add("farm2.config.sys.title.foot");
        ableKeys.add("farm2.conf.server.version");
        if (ableKeys.contains(key.getKey())) {
            Object value = Farm2ConfigUtils.getInstance(Farm2ConfigEnum.FARM2_PROPERTIES).getData(key.getKey());
            if (value != null) {
                return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, value);
            }
            value = farmParameter.getObjectParameter(key.getKey());
            return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, value);
        } else {
            return FarmResponseResult.getInstance(FarmResponseCode.SUCESS, "NO-AUTH");
        }
    }

    @Operation(summary = "刷新系统缓存", description = "")
    @PostMapping("/clearcache")
    public FarmResponseResult clearCache() {
        FarmCaches.getInstance().clearAllCache();
        return FarmResponseResult.getInstance(FarmResponseCode.SUCESS);
    }
}
